/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.chooser.view;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Collection;
import java.util.ResourceBundle;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import offset.nodes.Constants;
import offset.nodes.client.chooser.model.FolderNode;
import offset.nodes.client.model.ActivePanelContainer;

/**
 *
 * @author Walter Lütgenau
 */
public class QueryResultChooserPanel extends javax.swing.JPanel {

    FolderNode selectedNode = null;
    FolderNode[] nodes;
    public static final int COLUMN_NAME = 0;
    public static final int COLUMN_PATH = 1;
    public static final int COLUMN_NAME_WIDTH = 100;
    ResourceBundle bundle = java.util.ResourceBundle.getBundle("offset/nodes/client/view/resources/ClientBundle"); // NOI18N
    ActivePanelContainer container = null;
    private static final KeyStroke ENTER_KEY = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
    static final String ENTER_ACTION = "EnterDefaultButton";

    /** Creates new form NodeQueryChooserDialog */
    public QueryResultChooserPanel(Collection<FolderNode> nodes) throws Exception {
        this.nodes = nodes.toArray(new FolderNode[nodes.size()]);
        initComponents();
        init(nodes);
    }

    public void setContainer(ActivePanelContainer container) {
        this.container = container;
    }

    public FolderNode getSelectedNode() {
        return selectedNode;
    }

    class FolderNodeTableModel extends AbstractTableModel {

        public String getColumnName(int col) {
            switch (col) {
                case COLUMN_NAME:
                    return bundle.getString("resultChooser.columnName");

                case COLUMN_PATH:
                    return bundle.getString("resultChooser.columnPath");

                default:
                    return "";
            }
        }

        @Override
        public int getColumnCount() {
            return 2;
        }

        @Override
        public int getRowCount() {
            return nodes.length;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            switch (columnIndex) {
                case COLUMN_NAME:
                    return nodes[rowIndex].getName();

                case COLUMN_PATH:
                    return getParent(nodes[rowIndex].getPath());

                default:
                    return "";
            }
        }
    }

    protected String getParent(String path) {
        int last = path.lastIndexOf(Constants.PATH_SEPARATOR);
        if (last < 0)
            return path;

        return path.substring(0, last);
    }

    class FolderNodeSelectionListener implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (availableTable.getSelectedRow() < 0 || availableTable.getSelectedRow() > nodes.length)
                return;

            selectedNode = nodes[availableTable.convertRowIndexToModel(availableTable.getSelectedRow())];
            selectedTextField.setText(selectedNode.getPath());

            if (container != null)
                container.enableOkButton(true);
        }
    }

    class DoubleClickAdapter extends MouseAdapter {

        @Override
        public void mousePressed(MouseEvent e) {
            if (container != null && e.getClickCount() == 2 && !availableTable.isEditing())
                container.executeOk();
        }

    }

    protected void init(Collection<FolderNode> nodes) {
        availableTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        availableTable.getSelectionModel().addListSelectionListener(new FolderNodeSelectionListener());
        availableTable.getColumnModel().getColumn(COLUMN_NAME).setPreferredWidth(COLUMN_NAME_WIDTH);
        availableTable.getColumnModel().getColumn(COLUMN_PATH).setPreferredWidth(COLUMN_NAME_WIDTH * 4);

        availableTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ENTER_KEY, ENTER_ACTION);
        availableTable.getActionMap().put(ENTER_ACTION, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (container != null)
                    container.executeOk();
            }
        });

        availableTable.addMouseListener(new DoubleClickAdapter());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        availableLabel = new javax.swing.JLabel();
        selectedLabel = new javax.swing.JLabel();
        selectedTextField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        availableTable = new javax.swing.JTable();

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("offset/nodes/client/view/resources/ClientBundle"); // NOI18N
        availableLabel.setText(bundle.getString("resultChooser.resultNode")); // NOI18N

        selectedLabel.setText(bundle.getString("resultChooser.selected")); // NOI18N

        selectedTextField.setBackground(java.awt.SystemColor.text);
        selectedTextField.setEditable(false);

        availableTable.setAutoCreateRowSorter(true);
        availableTable.setModel(new FolderNodeTableModel());
        jScrollPane1.setViewportView(availableTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 879, Short.MAX_VALUE)
                    .addComponent(availableLabel, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(selectedTextField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 879, Short.MAX_VALUE)
                    .addComponent(selectedLabel, javax.swing.GroupLayout.Alignment.LEADING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(availableLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(selectedLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(selectedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26))
        );
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel availableLabel;
    private javax.swing.JTable availableTable;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel selectedLabel;
    private javax.swing.JTextField selectedTextField;
    // End of variables declaration//GEN-END:variables
}
